package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.model.Product;
import cn.ncu.wechat.model.User;
import cn.ncu.wechat.model.WechatPay;
import cn.ncu.wechat.model.dto.OrderDTO;
import cn.ncu.wechat.model.dto.OrderDTO2;
import cn.ncu.wechat.model.dto.VerificationDTO;
import cn.ncu.wechat.service.ProductService;
import cn.ncu.wechat.service.UserService;
import cn.ncu.wechat.service.WeChatPayService;
import cn.ncu.wechat.util.Result;
import cn.ncu.wechat.util.StringUtil;
import cn.ncu.wechat.vo.OrderVo;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ncu.wechat.model.Orders;
import cn.ncu.wechat.service.OrdersService;
import cn.ncu.wechat.dao.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 
 * @description 针对表【order(订单表)】的数据库操作Service实现
 * @createDate 2025-01-07 16:15:26
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService{
    @Value("${cn.ncu.key}")
    private String key;

    @Value("${cn.ncu.PointConversion}")
    private float PointConversion;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private WeChatPayService weChatPayService;

    @Autowired
    private UserService userService;

    /**
     * 创建订单使用时间戳＋产品id+用户id作为订单编号
     * */
    public Result<?> AddOrder(OrderVo orderVo,String token){
        try {
            Orders orders = new Orders();
            orders.setProductId(orderVo.getProductId());
            orders.setQuantity(orderVo.getQuantity());
            Product product =  productService.getById(orderVo.getProductId());
            orders.setProductImage(product.getImage());
            if(orderVo.isUsePoints()){
                orders.setUsePoints(1);
            } else orders.setUsePoints(0);
            Algorithm algorithm = Algorithm.HMAC256(key);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            System.out.println("token="+token);
            DecodedJWT decodedJWT = jwtVerifier.verify(token.substring(7));
            orders.setUserId(decodedJWT.getClaim("id").asLong());
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmS");
            String OrderId = dateFormat.format(date)+ orders.getUserId();
            orders.setOrderNo(OrderId);
            orders.setAmount(product.getPrice().multiply(BigDecimal.valueOf(orderVo.getQuantity())));
            orders.setProductName(product.getName());
            orders.setStatus(1);
            ordersMapper.insert(orders);
            JSONObject jsonObject = new JSONObject();
            //计算金额




            jsonObject.put("amount",orders.getAmount());
            jsonObject.put("orderNo",OrderId);
            return Result.success(jsonObject);
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }
    }


    /*
     * 订单合理性校验
     *
     * */
    public int checkOrder(OrderVo orderVo){
        int check = 500;
        if (orderVo.getQuantity()<=0){
            check = 400;
        }
        else {
            Product product = productService.getById(orderVo.getProductId());
            System.out.println("product=="+product);
            // 检查商品是否存在
            if (product == null) {
                check=404;
            }
            // 比较库存是否满足下单量
            else if (orderVo.getQuantity() > product.getStock()) {
                check=400;
            }
            else check=200;
        }
        return check;
    }

    /**
     * 获取订单
     * */
    public Result<?> getOrdersByKey(Integer page,Integer pageSize,Integer status){

        try {
            List<Orders> orders = null;
            Page<Orders> pageInfo = new Page<>(page, pageSize);
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.select("order_no","product_name","product_image","amount","status","create_time");
            if (status!=0){
                queryWrapper.eq("status",status);
            }
            Page<Orders> ordersPage = ordersMapper.selectPage(pageInfo,queryWrapper);
            orders = ordersPage.getRecords();
            List<Map<String,Object>> result = orders.stream().map(order -> {
                        Map<String, Object> orderMap = new HashMap<>();
                        orderMap.put("orderNo", order.getOrderNo());
                        orderMap.put("productName", order.getProductName());
                        orderMap.put("image", order.getProductImage());
                        orderMap.put("amount", order.getAmount());
                        orderMap.put("status", order.getStatus());
                        orderMap.put("createTime", order.getCreateTime());
                        return orderMap;
                    })
                    .collect(Collectors.toList());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",result);
            jsonObject.put("total",ordersPage.getTotal());
            return Result.success(jsonObject);
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }
    }

    public Result<?> getOrderDetail(String orderNo){
        try {
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.select("order_no","product_name","amount","product_image","amount","status","create_time");
            queryWrapper.eq("order_no",orderNo);
            Orders order = ordersMapper.selectOne(queryWrapper);
            if (order!=null){
                OrderDTO orderDTO = new OrderDTO();
                orderDTO.setImage(order.getProductImage());
                orderDTO.setAmount(order.getAmount());
                orderDTO.setOrderNo(order.getOrderNo());
                orderDTO.setProductName(order.getProductName());
                orderDTO.setStatus(order.getStatus());
                orderDTO.setCreateTime(order.getCreateTime());
                orderDTO.setPayTime(order.getPayTime());
                orderDTO.setVerificationCode(order.getVerificationCode());
                orderDTO.setVerificationTime(order.getVerificationTime());
                return Result.success(orderDTO);
            } else return Result.error(404,"订单不存在");
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }
    }

    public boolean updateOrder(String orderNo,int status,boolean verification,String refundReason,String payTime) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status",status);
        updateWrapper.set("update_time",new Date(System.currentTimeMillis()));
        updateWrapper.eq("order_no",orderNo);
        if (StringUtil.IsNotNull(refundReason)){
            updateWrapper.set("refund_reason",refundReason);
        }
        if (StringUtil.IsNotNull(payTime)){
            updateWrapper.set("refund_reason",payTime);
        }
        if (verification){
            updateWrapper.set("verification_code", UUID.randomUUID().toString().replace("-", ""));
        }
        return ordersMapper.update(updateWrapper)==1;
    }

    /**
     * 调用微信接口发起预支付，修改订单状态为待支付并返回预支付信息给前端
     * */
    public Result<?> payOrder(String orderNo){
        try {
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no",orderNo);
            Orders orders = ordersMapper.selectOne(queryWrapper);
            if (orders!=null){
                User user= userService.getById(orders.getUserId());
                Map<String,String> data = weChatPayService.createMiniProgramPayment(user.getOpenId(),orders,null);
                if (data.get("failReason")!=null){
                    return Result.fail(500,"服务器错误:"+data.get("failReason"));
                }
                data.remove("appId");
                if (!updateOrder(orderNo,1,false,null,null)){
                    return Result.success(data,"订单生成成功,服务器数据出现错误，请联系服务器后台管理员");
                }
                return Result.success(data);
            }
            return Result.fail(400,"订单不存在");
        } catch (Exception e){
            return Result.fail(500,"服务器错误，订单创建失败");
        }
    }

    public Result<?> getOrderListByKey(Integer page,Integer pageSize,Integer status,String orderNo,String phone){
        try {
            OrderDTO2 orderVo = new OrderDTO2();
            orderVo.setOrderNo(orderNo);
            orderVo.setPhone(phone);
            orderVo.setStatus(status);
            List<OrderVo> ordersList = ordersMapper.getOrderListByKey(orderVo);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",ordersList);
            jsonObject.put("total",ordersList.size());
            return Result.success(jsonObject);
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }
    }

    public Result<?> getVerifications(Integer page,Integer pageSize,String orderNo,String startDate,String endDate,Integer storeId){
        try {
            if (page==null||page<=0||pageSize==null||pageSize<=0){
                return Result.fail(400,"参数错误");
            }
            Page<VerificationDTO> pageInfo = new Page<>(page, pageSize);
            Page<VerificationDTO> verificationDTOPage = ordersMapper.getOrderListForVif(pageInfo,orderNo,startDate,endDate,storeId);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",verificationDTOPage.getRecords());
            jsonObject.put("total",verificationDTOPage.getTotal());
            return Result.success(jsonObject);
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }
    }

    //需求中未指明退款后续逻辑，商品是否归还
    public Result<?> refundOrder(String ordersNo,String reason){
        try{
            Orders orders = ordersMapper.selectOne(new QueryWrapper<Orders>().eq("order_no",ordersNo).select("amount"));
            System.out.println( "order- "+ordersNo+":"+weChatPayService.refund(orders));
            if (updateOrder(ordersNo,4,false,reason,null)){
                return Result.success("申请退款成功");
            }
            else return Result.fail(404,"订单不存在");
        }
        catch (RuntimeException e){
            return Result.error(500,"微信申请服务器错误："+e);
        }
        catch (Exception e){
            return Result.error(500,"服务器错误:"+e);
        }
    }
}